package com.topscomm.file.upload;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.springframework.stereotype.Component;

import com.topscomm.file.FileInfoDTO;

import lombok.extern.slf4j.Slf4j;

/**
 * 文件上传
 * 
 * @description:
 * @author: donghang
 * @date: 2021年3月19日上午12:00:21
 * @modify:
 */
@Component
@Slf4j
public class FileUploadDispatcher {
	/**
	 * 线程调度
	 */
	private ExecutorService executorService;

	public FileUploadDispatcher() {
		Integer availableProcessors = Runtime.getRuntime().availableProcessors();
		Integer numOfThreads = availableProcessors * 2;
		executorService = Executors.newCachedThreadPool();
		// new ThreadPoolExecutor(numOfThreads, numOfThreads, 60L,
		// TimeUnit.MILLISECONDS,
		// new LinkedBlockingDeque<Runnable>(5));
	}

	/**
	 * 处理文件
	 * 
	 * @description:
	 * @author: donghang
	 * @date: 2021年3月15日下午8:15:36
	 * @modify:
	 */
	public boolean handle(FileInfoDTO fileInfo) {
		// 提交到线程。进行文件上传
		try {
			Future<Boolean> future = executorService.submit(new FileUploadTask(fileInfo));
			if (future.get() == true) {
				return true;
			}
		} catch (Exception e) {
			log.error("文件" + fileInfo.getFileDirPath() + "上传失败");
			return false;
		}
		return false;
	}
}
